<!--
 * @Author: YWY
 * @Date: 2022-02-23 11:40:38
 * @LastEditors: YWY
 * @LastEditTime: 2022-03-07 16:37:11
-->
<template>
  <div class="userpage">
    <button class="userpage_return" @click="returnBtn">
      <van-icon name="arrow-left"></van-icon>返回
    </button>
    <button class="logout" @click="toLogout">退出登录</button>
    <div>
      <img :src="avatar" alt="" class="userImg" @click="showPreview" />
      <p>{{ name }}</p>
      <div class="userpage_count">
        <div class="userpage_count_box">
          <p>{{ follows.length }}</p>
          <p>关注</p>
        </div>
        <div class="userpage_count_fans">
          <p>{{ fans.length }}</p>
          <p>粉丝</p>
        </div>
        <div class="userpage_count_box">
          <p>{{ likes }}</p>
          <p>收到的赞</p>
        </div>
      </div>
    </div>

    <van-collapse v-model="mainActiveName" accordion>
      <!-- 我的资料 -->
      <van-collapse-item title="我的资料" name="1">
        <!-- 编辑区 -->
        <div>
          <!-- <button class="user_dataSave" @click="upload">保存</button> -->
          <!-- 用户名更改 -->
          <van-field
            name="uploader"
            label="用户名"
            v-model="nameInput"
            :colon="true"
          >
            <template>
              <p>{{ name }}</p>
            </template>
          </van-field>
          <!-- 头像更改 -->
          <van-field name="uploader" label="头像上传" :colon="true">
            <template #input>
              <van-uploader
                v-model="pic"
                multiple
                :max-count="1"
                :max-size="500 * 1024"
                @oversize="onOversize"
                result-type="file"
                :preview-image="true"
              />
            </template>
          </van-field>
          <!-- 性别更改 -->
          <van-field name="radio" label="性别" :colon="true">
            <template #input>
              <van-radio-group v-model="sex" direction="horizontal">
                <van-radio name="男">男</van-radio>
                <van-radio name="女">女</van-radio>
                <van-radio name="保密">保密</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <!-- 城市更改 -->
          <van-field
            v-model="city"
            is-link
            readonly
            name="picker"
            label="城市"
            placeholder="点击选择城市"
            @click="showPicker = true"
            :colon="true"
          />
          <van-popup v-model:show="showPicker" position="bottom">
            <van-picker
              :columns="columns"
              @confirm="cityConfirm"
              @cancel="showPicker = false"
            />
          </van-popup>
          <van-button
            round
            block
            type="primary"
            native-type="submit"
            @click="upload"
          >
            保存修改
          </van-button>
        </div>
      </van-collapse-item>
      <!-- 我的文章 -->
      <van-collapse-item title="我的文章" name="2">
        <post-cell-in-user
          v-for="item in user.article"
          :key="item.id"
          :title="item.title"
          :author="item.user_name"
          :postTime="item.postTime"
          :likes="item.likes"
          :replies="item.comments"
          :visits="item.visits"
          :createdAt="item.createdAt"
          :updatedAt="item.updatedAt"
          :cover_url="item.cover_url"
          :content="item.content"
          :cover="item.cover_url"
          :status="item.status"
          @click="toAritclePage(item.id)"
        ></post-cell-in-user>
        <div v-if="!article.length">没有写过文章</div>
      </van-collapse-item>
      <!-- 我的收藏 -->
      <van-collapse-item title="我的收藏" name="3">
        <post-cell
          v-for="item in user.favorite"
          :key="item.article_id"
          :title="item.articleInfo.title"
          :author="item.articleInfo.name"
          :postTime="item.postTime"
          :likes="item.articleInfo.likes"
          :replies="item.articleInfo.comments"
          :visits="item.articleInfo.visits"
          :createdAt="item.articleInfo.createdAt"
          :updatedAt="item.articleInfo.updatedAt"
          :cover_url="item.articleInfo.cover_url"
          :content="item.articleInfo.summary"
          :cover="item.articleInfo.cover_url"
          @click="toAritclePage(item.article_id)"
        ></post-cell>
        <div v-if="!favorite.length">没有收藏的文章</div>
      </van-collapse-item>
      <!-- 我的关注 -->
      <van-collapse-item title="我的关注" name="4">
        <div v-for="item in follows" :key="item.id" class="user_follows_cell">
          <img :src="item.follow_pic" alt="" class="user_follower_avatar" />
          <p>{{ item.follow_name }}</p>
          <div class="user_delet_follower">
            <van-icon
              name="cross"
              @click="user.deletFollower(item.follow_id)"
            ></van-icon>
          </div>
        </div>
        <div v-if="!follows.length">还没关注任何人</div>
      </van-collapse-item>
      <!-- 我的粉丝 -->
      <van-collapse-item title="我的粉丝" name="5">
        <div
          v-for="item in fans"
          :key="item.id"
          class="user_fans_cell"
          @click="toUserPage(item.id)"
        >
          <img :src="item.img" alt="" class="user_fans_avatar" />
          <p>{{ item.user_name }}</p>
        </div>
        <div v-if="!fans.length">没有人关注我</div>
      </van-collapse-item>
      <!-- 修改密码 -->
      <van-collapse-item title="修改密码" name="6">
        <div>
          <van-form>
            <van-cell-group inset>
              <van-field
                label="旧密码*"
                :colon="true"
                v-model="oldPassword"
                name="pattern"
                type="password"
                placeholder="请输入旧密码"
                :rules="[{ pattern, message: '请输入6~18位字符' }]"
              />
              <van-field
                label="新密码*"
                :colon="true"
                v-model="newPassword"
                name="validator"
                type="password"
                placeholder="请输入新密码"
                :rules="[{ pattern, message: '请输入6~18位字符' }]"
              />
              <van-field
                label="确认新密码*"
                :colon="true"
                v-model="confirmPassword"
                name="validatorMessage"
                type="password"
                placeholder="请确认新密码"
                :rules="[{ validator, message: '请输入两次相同的密码' }]"
              />
            </van-cell-group>
            <div style="margin: 16px">
              <van-button
                round
                block
                type="primary"
                native-type="submit"
                @click="toChangePassword"
              >
                提交
              </van-button>
            </div>
          </van-form>
        </div>
      </van-collapse-item>
    </van-collapse>
  </div>
</template>
<script>
import { defineComponent, ref } from "vue";
import PostCellInUser from "@/components/PostCellInUser.vue";
import PostCell from "@/components/PostCell.vue";
import { storeToRefs } from "pinia";
import { userStore } from "@/store/userdata.js";
import { Toast, ImagePreview } from "vant";
import { useRouter } from "vue-router";
import { changePassword, updateToken } from "../api/services/user.service";
import { mainStore } from "../store";
import { colseWsConnection } from "../utils/ws/wsUtils";
export default defineComponent({
  name: "UserPage",
  components: {
    PostCellInUser,
    PostCell,
    [ImagePreview.Component.name]: ImagePreview.Component,
  },
  setup() {
    const user = userStore();
    const main = mainStore();
    const router = useRouter();
    const mainActiveName = ref("1");
    const columns = ["杭州", "宁波", "温州", "嘉兴", "湖州"];
    const showPicker = ref(false);
    const {
      avatar,
      pic,
      city,
      sex,
      name,
      article,
      favorite,
      follows,
      fans,
      likes,
      nameInput,
    } = storeToRefs(user);
    const oldPassword = ref("");
    const newPassword = ref("");
    const confirmPassword = ref("");
    const showChangePassword = ref(false);
    //刷新页面重新获取信息
    user.init();
    nameInput.value = name.value;
    //头像预览
    const showPreview = () => {
      ImagePreview({
        images: [avatar.value],
        closeable: true,
      });
    };

    // 登出
    const toLogout = () => {
      localStorage.removeItem("Authorization");
      main.logState = false;
      Toast("已注销");
      router.push({ path: "/login" });
      let timer = main.wsTimer;
      clearInterval(timer);
      main.$patch((state) => {
        state.wsTimer = null;
      });
      colseWsConnection();
    };
    //返回按钮
    const returnBtn = () => {
      window.history.back();
    };

    // 用户资料上传
    const upload = () => {
      user
        .upload()
        .then((res) => {
          Toast.success("用户资料修改成功");
          // location.reload();
        })
        .catch((rej) => {
          Toast.fail("用户资料修改失败");
        });
    };

    //头像过大
    const onOversize = (file) => {
      console.log(file);
      Toast("文件大小不能超过 500kb");
    };

    //确认城市
    const cityConfirm = (value) => {
      city.value = value;
      showPicker.value = false;
    };

    //密码格式验证正则
    const pattern = /[\d\w]{6,16}/;

    //验证两次输入的新密码是否相同
    const validator = () => {
      if (confirmPassword.value !== newPassword.value) {
        return false;
      }
      return true;
    };

    //提交修改密码
    const toChangePassword = () => {
      if (!validator()) {
        Toast("两次输入密码不同");
      } else if (!pattern.test(oldPassword)) {
        Toast("旧密码格式错误");
      } else {
        changePassword(confirmPassword.value, oldPassword.value)
          .then((res) => {
            console.log(res);
            Toast("修改密码成功");
          })
          .catch((rej) => {
            console.log(rej);
            Toast("旧密码错误");
          });
      }
    };

    //跳转文章页
    const toAritclePage = (id) => {
      router.push({ path: `/article/${id}` });
    };

    return {
      user,
      mainActiveName,
      avatar,
      city,
      pic,
      sex,
      name,
      columns,
      showPicker,
      oldPassword,
      newPassword,
      confirmPassword,
      showChangePassword,
      pattern,
      article,
      favorite,
      follows,
      fans,
      likes,
      nameInput,
      showPreview,
      cityConfirm,
      validator,
      toLogout,
      upload,
      onOversize,
      toChangePassword,
      returnBtn,
      toAritclePage,
    };
  },
});
</script>
<style lang='less'>
.logout {
  position: absolute;
  font-size: 12px;
  top: 15px;
  right: 15px;
  border: none;
  color: gray;
  background-color: #dee1e6;
  border-radius: 5px;
  padding: 4px 10px;
  box-shadow: 0 0 2px 1px gray;
}
.user_dataSave {
  font-size: 12px;
  border: none;
  color: gray;
  background-color: #dee1e6;
  border-radius: 5px;
  padding: 4px 10px;
  box-shadow: 0 0 2px 1px gray;
  z-index: 11;
  position: absolute;
  width: 50px;
  height: 30px;
  line-height: 12px;
  right: 10px;
  top: 50px;
}
.userImg {
  width: 100px;
  border-radius: 50%;
  box-shadow: 0 0 2px 1px gray;
  margin-top: 50px;
  background-color: white;
}
.userpage {
  background-color: rgb(227, 238, 255);
  height: 100vh;
  width: 100vw;
  .van-button--block {
    width: 300px;
    margin: 0 auto;
  }
  .userpage_return {
    position: absolute;
    font-size: 16px;
    top: 14px;
    left: 7px;
    border: none;
    color: gray;
    background-color: transparent;
    border-radius: 5px;
  }
  .van-grid {
    padding: 5px;
    border-radius: 15px;
    background-color: white;
  }
  .van-collapse-item {
    box-shadow: 0 0 1px;
  }
  .van-collapse-item__title--expanded {
    background-color: rgb(235, 235, 235);
  }
  .van-cell {
    z-index: 10;
  }
  .userpage_count {
    display: flex;
    justify-content: space-between;
    background-color: white;
    box-shadow: 0 0 1px 0 gray;
    .userpage_count_box {
      margin: 0 20px;
      flex: 0 100px;
      p {
        text-align: center;
        // border: 1px solid black;
        color: rgb(150, 151, 153);
      }
    }
    .userpage_count_fans {
      flex: 1;
      margin: 0 20px;
      p {
        text-align: center;
        // border: 1px solid black;
        color: rgb(150, 151, 153);
      }
    }
  }
  .user_follows_cell {
    display: flex;
    // border: 1px solid black;
    justify-content: space-between;
    width: 300px;
    margin: 10px auto;
    align-items: center;
    .user_follower_avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      // border: 1px solid black;
    }
    p {
      flex: 0 100px;
      text-align: left;
      // border: 1px solid black;
    }
    .user_delet_follower {
      // border: 1px solid black;
      .van-icon {
        font-size: 20px;
      }
    }
  }
  .user_fans_cell {
    display: flex;
    // border: 1px solid black;
    justify-content: space-between;
    width: 250px;
    margin: 10px auto;
    align-items: center;
    .user_fans_avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      // border: 1px solid black;
    }
    p {
      flex: 0 100px;
      text-align: left;
      // border: 1px solid black;
    }
  }
}
</style>